#include <iostream>
#include <memory>
#include <algorithm>
#include "Tcpsever.hpp"
#include "Comm.hpp"
#include "Translate.hpp"
//./tcp_server 端口号
void Usage(std::string str)
{
    std::cout << "usage:\n\t" << str << "local_port\n"
              << std::endl;
}
TransLate trans;
void Interact(int sockfd,std::string &out,const std::string& in)
{
    char buffer[1024];                                    // 字符数组没有‘\0’
    ssize_t n = read(sockfd,buffer, sizeof(buffer) - 1); // 留出最后一个空间'\0'
    if (n > 0)
    {
        buffer[n] = 0; // 给末尾添加‘\0’,终止字符串信息
        write(sockfd, in.c_str(), in.size());
    }
    else if (n == 0) // 对方关闭了连接
    {
        lg.LogMessage(Info, "clinet quit\n");
    }
    else
    {
        lg.LogMessage(Error, "read socket error\n");
    }
}
void Ping(int sockfd, InetAddr addr)
{
    lg.LogMessage(Debug, "%s selsect %s successful sockfd:%d\n", addr.PrintDebug().c_str(), "ping", sockfd);
    std::string message;
    Interact(sockfd,message,"Pong");
}


void Translate(int sockfd, InetAddr addr)
{
    lg.LogMessage(Debug, "%s selsect %s successful sockfd:%d\n", addr.PrintDebug().c_str(), "translate", sockfd);
    std::string word;
    char wordbuf[128];
    int n = read(sockfd,wordbuf,sizeof(wordbuf)-1);//读客户端发来的单词
    if(n>0)
    {
        wordbuf[n] ='\0';
    }
    std::string chinese = trans.Excute(wordbuf);
    write(sockfd,chinese.c_str(),chinese.size());
    lg.LogMessage(Debug,"%s translate servie,%s->%s\n",addr.PrintDebug(),wordbuf,chinese.c_str());

}
void Transform(int sockfd,InetAddr addr)//大小写转换
{
    lg.LogMessage(Debug, "%s selsect %s successful sockfd:%d\n", addr.PrintDebug().c_str(), "transform", sockfd);
    char wordbuf[128];
    int n = read(sockfd,wordbuf,sizeof(wordbuf)-1);
    if(n > 0) wordbuf[n] = 0;

     std::string low = wordbuf;
    // for(auto &c : wordbuf)
    // {
    //     low+=std::tolower(c);
    // }
    std::transform(low.begin(),low.end(),low.begin(),[](unsigned char c){return std::tolower(c);});
    write(sockfd,low.c_str(),low.size());
    lg.LogMessage(Debug,"%s transform servie,%s->%s\n",addr.PrintDebug(),wordbuf,low.c_str());

}   
int main(int argc, char **argv)
{
    if (argc != 2)
    {
        Usage(argv[0]);
        return usage_err;
    }
    uint16_t port = std::stoi(argv[1]);
    std::unique_ptr<Tcpserver> tsvr = std::make_unique<Tcpserver>(port);
    tsvr->RegisterFunc("ping", Ping);
    tsvr->RegisterFunc("translate", Translate);
    tsvr->RegisterFunc("transform",Transform);
    tsvr->Init();
    tsvr->Start();
    return 0;
}